import { useUserStore } from '~/stores/modules/user';

// 客户端请求
type FetchType = typeof $fetch;
export type FetchOptions = Parameters<FetchType>[1];

export const useClientRequest = <T = unknown>(url: string, opts?: FetchOptions) => {
    const token = useUserStore().token;

    const defaultOptions: FetchOptions = {
        baseURL: '',
        onRequest({ options }) {
            options.headers = (options.headers || {}) as { [key: string]: string };
            // 如果有token，则添加到请求头中
            if (token) {
                options.headers.Authorization = 'Bearer ' + token;
            }
        },
        onResponse({ response }) {
            if (response.status !== 200) {
                ElMessage.error(response._data.msg);
            }
        },
        onResponseError({ response }) {
            console.log(response);
            ElMessage.error(response._data.data.msg);
        },
    };

    return $fetch<T>(url, { ...defaultOptions, ...opts });
};
